package com.ze.familyday.familyphotoframesquare;

import java.io.File;
import java.util.concurrent.ExecutorService;

import org.json.JSONObject;

import com.mouse.customview.CustomDialog;
import com.mouse.customview.CustomToast;
import com.ze.commontool.NetHelper;
import com.ze.commontool.UpdateTools;
import com.ze.commontool.UpdateTools.DownloadCallback;
import com.ze.familyday.familyphotoframesquare.R;
import com.ze.model.ModelDataMgr;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class BaseActivity extends Activity{
	
	
	public void checkVersion(ExecutorService executorService, final int what, final Handler handler )
	{
    	executorService.submit(new Runnable() {
			
			@Override
			public void run() {
				String respon = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_updatecheck));
				try {
					if (respon != null  && !respon.equals("")) {
						JSONObject object = new JSONObject(respon);
						if (object.getInt("error") == 0 ) {
							object = object.getJSONObject("data");
							String version = object.getString("version");
//							Message msg = handler.obtainMessage(10086);
							Message msg = handler.obtainMessage(what);
							msg.obj = version;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void download()
	{
		downProgressBar = new ProgressDialog(this);
		updateTools = new UpdateTools(callback, getResources().getString(R.string.http_update) 
				/*"http://www.familyday.com.cn/app/test/FamilyCubeV1.7.apk"*/
					, ModelDataMgr.CUBE_FILE_DIR, "cube.apk");
		updateTools.download(this, updateTools.handler);
		downProgressBar.setMessage("更新中...");
		downProgressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downProgressBar.setCanceledOnTouchOutside(false);
		downProgressBar.show();
	}
	UpdateTools updateTools;
	DownloadCallback callback = new DownloadCallback() {
		
		@Override
		public void updateDownloadProgress(int cur_size) {
			downProgressBar.setMax(updateTools.fileSize);
			downProgressBar.setProgress(cur_size);
		}
		
		@Override
		public void notifyDownError() {
			downProgressBar.hide();
			CustomToast.show(BaseActivity.this, R.string.loading_error);
		}
		
		@Override
		public void finishDownload() {
			
			Intent intent = new Intent();
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setAction("android.intent.action.VIEW.INSTALL");
			intent.setDataAndType(Uri.fromFile(new File( ModelDataMgr.CUBE_FILE_DIR + "cube.apk") ),
			                                "application/vnd.android.package-archive");
			startActivity(intent);
		}
	};
	ProgressDialog downProgressBar;
	
}
